﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using v8sharp;

namespace HostingSample
{
	public partial class MainWindow : Form, IWindow, IApplicationConsole
	{
		V8Engine engine;

		internal MainWindow(V8Engine engine) {
			InitializeComponent();

			this.engine = engine;
		}

		public string CaptionText {
			get {
				return Text;
			}
			set {
				Text = value;
			}
		}

		void btnRun_Click(object sender, System.EventArgs e) {
			var script = engine.Compile(scriptBox.Text);
			if (script.HasExceptions) {
				MessageBox.Show(script.Exceptions[0].Message);
			} else {
				try {
					engine.Execute(script);
				} catch (Exception err) {
					MessageBox.Show(err.Message);
				}
			}
		}

		void IApplicationConsole.Write(string message) {
			if (consoleWindow.TextLength > 0) {
				consoleWindow.Text += Environment.NewLine;
			}

			consoleWindow.Text += message;
		}

		void IApplicationConsole.WriteFunction(Delegate function) {
			Object result = ((v8sharp.V8Function)function)(null);
			string message = result == null ? "Function returned null" : "Function result: " + result.ToString();

			((IApplicationConsole)this).Write(message);
		}

		void IApplicationConsole.Clear() {
			consoleWindow.Text = "";
		}
	}
}
